﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;
using seejee_Backendium.Data.DbContest;
using seejee_Backendium.Data.Services;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace seejee_Backendium.WEB.Controllers
{
    [ApiController]
    [Route("api/")]
    [Authorize]
    public class StoreController : ControllerBase
    {
        private readonly IStoreService _storeService;
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration; // 新增字段
        private readonly ILogger<StoreController> _logger;

        public StoreController(IStoreService storeService, IConfiguration configuration, ILogger<StoreController> logger, ApplicationDbContext context)
        {
            _storeService = storeService;
            _configuration = configuration;
            _logger = logger; // 
            _context = context; // 注入 ApplicationDbContext
        }

        // 获取存储过程列表
        [HttpGet("store/list")]
        public IActionResult GetStore([FromQuery] int pageIndex, [FromQuery] int pageSize, [FromQuery] string keyword = "")
        {
            if (pageIndex < 1 || pageSize < 1)
            {
                return BadRequest(new { success = false, message = "参数错误" });
            }
            try
            {
                var stores = _storeService.GetStore(pageIndex, pageSize, keyword);
                return Ok(new { success = true, data = stores });
            }
            catch (Exception ex)
            {
                // 可选：记录日志
                return StatusCode(500, new { success = false, message = ex.Message });
            }

        }


        // 获取存储过程名称
        [HttpGet("store/storeName")]
        public async Task<IActionResult> GetStoreName()
        {
            try
            {
                var stores = await _storeService.GetStoreName();
                return Ok(new
                {
                    success = true,
                    data = new
                    {
                        items = stores,  // 明确使用items字段
                        total = stores.Count()
                    },
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取存储过程失败");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取存储过程失败",
                    error = ex.Message
                });
            }
        }

        // 获取视图名称
        //[HttpGet("view/viewName")]
        //public async Task<IActionResult> GetViewName(string cCusName)
        //{
        //    try
        //    {
        //        var views = await _storeService.GetViewName(cCusName);
        //        return Ok(new
        //        {
        //            success = true,
        //            data = new
        //            {
        //                code=200,
        //                items = views,  // 明确使用items字段
        //                total = views.Count()
        //            },
        //            message = "查询成功"
        //        });
        //    }
        //    catch (Exception ex)
        //    {
        //        _logger.LogError(ex, "获取视图名称失败");
        //        return StatusCode(500, new
        //        {
        //            success = false,
        //            message = "获取视图名称失败",
        //            error = ex.Message
        //        });
        //    }
        //}
        // 获取存储过程内容
        [AllowAnonymous]
        [HttpGet("store/procedures/{cStoreName}")]
        public async Task<IActionResult> GetStore(string cStoreName)
        {
            try
            {
                var stores = await _storeService.GetStore(cStoreName);
                return Ok(new
                {
                    success = true,
                    data = new
                    {
                        items = stores,  // 明确使用items字段
                        total = stores.Count()
                    },
                    message = "查询成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取存储过程失败");
                return StatusCode(500, new
                {
                    success = false,
                    message = "获取存储过程失败",
                    error = ex.Message
                });
            }
        }
 
        //添加存储过程
        [HttpPost("store/insert")]
        public async Task<IActionResult> InsertStore([FromBody] StoreInsertDTO store)
        {
            var stores = new StoreInsertDTO
            {
                cStoreName = store.cStoreName,
                cStoredProcedures = store.cStoredProcedures,
                cComment = store.cComment,
                dCreateTime = store.dCreateTime,
                //iCusID = store.iCusID
            };
            var result = _storeService.InsertStore(stores);
            if (result)
                return Ok(new { Success = true, Message = "存储过程添加成功" });
            return StatusCode(500, new { Success = false, Message = "存储过程添加失败" });
        }


        //修改存储过程
        [HttpPut("store/update")]
        public IActionResult UpdateStore([FromBody] StoreInsertDTO store)
        {
            try
            {
                var result = _storeService.UpdateStore(store);
                if (result)
                    return Ok(new { Success = true, Message = "用户信息更新成功" });
                return StatusCode(500, new { Success = false, Message = "用户信息更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户信息更新失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
 
        // 删除存储过程
        [HttpDelete("store/delete/{cStoreName}")]
        public IActionResult DeleteStore(string cStoreName)
        {
            try
            {
                var result = _storeService.DeleteStore(cStoreName);
                if (result)
                    return Ok(new { Success = true, Message = "用户删除成功" });
                return StatusCode(500, new { Success = false, Message = "用户删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户删除失败");
                return StatusCode(500, new { Success = false, Message = "服务器错误" });
            }
        }
   

    }
}
